package pl.edu.pk.mech.kkbus.service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import org.springframework.stereotype.Service;

import pl.edu.pk.mech.kkbus.component.MyEntityManagerFactory;
import pl.edu.pk.mech.kkbus.entities.HistoryLog;
import pl.edu.pk.mech.kkbus.entities.User;
import pl.edu.pk.mech.kkbus.dto.Log;

@Service
public class HistoryLogService {
    
    EntityManagerFactory emf = MyEntityManagerFactory.get();
    
    public boolean create(long userId) {
        EntityManager em = null;        
        try {
            em = emf.createEntityManager();
            User user = em.find(User.class, new Long(userId));
            if (user == null) return false;
            
            user.getHistoryLogs().add(new HistoryLog(new Date()));
            em.persist(user);
        } finally {
            if (em != null)
                em.close();
        }        
        return true;
    }
    
    public List<Log> getHistoryLogForUser(long userId) {
        EntityManager em = null;
        try {
            em = emf.createEntityManager();
            User user = em.find(User.class, new Long(userId));
            if (user == null) return null;
            
            List<Log> result = new LinkedList<Log>();
            
            if(user.getHistoryLogs().size() > 0) {
                for (HistoryLog historyLog : user.getHistoryLogs()) {
                    result.add(new Log((historyLog.getKey().getId()), historyLog.getDate()));
                }
            }
            return result;
        } catch(NoResultException e) {
            return null;
        } finally {
            if (em != null)
                em.close();
        }
    }  
}
